package inftel.android;

import java.io.DataInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity implements OnClickListener {
	Button botonLogin, botonRegistro;
	EditText email;
	EditText pass;
	private final String ip = "192.168.1.135";
	private final String puerto = "14067";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        botonLogin = (Button) findViewById(R.id.button1);
        botonRegistro = (Button) findViewById(R.id.botonRegistro);
        botonLogin.setOnClickListener(this);
        botonRegistro.setOnClickListener(this);
        email = (EditText) findViewById(R.id.editText1);
		pass = (EditText) findViewById(R.id.editText2);
    }
    
    public void onClick(View v) {
		if(v == botonLogin){
			ProgressDialog dialog = ProgressDialog.show(Login.this, "","Comprobando identificación...", false,true);
			String emailUsuario = email.getText().toString();
			String passUsuario = pass.getText().toString();
			String servletURL = "http://"+ip+":"+puerto+
			"/ServiciosRedSocial-war/LoginServlet";
			try {
				URL ob = new URL(servletURL + "?email=" + emailUsuario + "&password="
					+ passUsuario);
				URLConnection conn = ob.openConnection();
				conn.setDoInput(true);
				conn.setDoOutput(true);
				InputStream in = conn.getInputStream();
				DataInputStream dis = new DataInputStream(in);
				String leido = dis.readLine();
				Log.i("LEIDO:", leido);
				dialog.hide();
				dialog.dismiss();
			if (leido.equals("0")) {
				CharSequence text = "Autenticacion incorrecta!";
				int duration = Toast.LENGTH_LONG;
				Toast toast = Toast.makeText(Login.this, text,duration);
				toast.show();
			} else {
				Intent miIntent = new Intent();
				miIntent.setClass(this,Bienvenido.class);
				miIntent.putExtra("email", emailUsuario);
				this.startActivity(miIntent);
				CharSequence text = "Autenticación correcta, bienvenido!";
				int duration = Toast.LENGTH_LONG;
				Toast toast = Toast.makeText(Login.this, text,duration);
				toast.show();
				this.startActivity(miIntent);
			}
			dis.close();
			conn = null;			
		} catch (Exception e) {
			Log.i("INFO", "Exception:" + e);
			
			e.printStackTrace();
		}
	}else if (v==botonRegistro){
		Intent miIntent = new Intent();
		miIntent.setClass(this,Registro.class);
		this.startActivity(miIntent);
	}
	}

}